package com.meiyuetao.myt.finance.web.action;

import java.util.Date;
import java.util.List;

import lab.s2jh.auth.entity.Role;
import lab.s2jh.auth.entity.User;
import lab.s2jh.auth.service.RoleService;
import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.audit.envers.ExtRevisionListener;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.service.Validation;
import lab.s2jh.core.web.view.OperationResult;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.hibernate.envers.RevisionType;
import org.springframework.beans.factory.annotation.Autowired;

import com.meiyuetao.myt.core.constant.VoucherStateEnum;
import com.meiyuetao.myt.core.constant.VoucherTypeEnum;
import com.meiyuetao.myt.core.service.VoucherNumGenerateService;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.finance.entity.TradeReceipt;
import com.meiyuetao.myt.finance.entity.TradeReceiptDetail;
import com.meiyuetao.myt.finance.service.AccountSubjectService;
import com.meiyuetao.myt.finance.service.BizTradeUnitService;
import com.meiyuetao.myt.finance.service.TradeReceiptService;

@MetaData("收款单")
public class ReceivablesReceiptController extends MytBaseController<TradeReceipt, Long> {
    @Autowired
    private TradeReceiptService tradeReceiptService;
    @Autowired
    private BizTradeUnitService bizTradeUnitService;
    @Autowired
    private VoucherNumGenerateService voucherNumGenerateService;
    @Autowired
    private AccountSubjectService accountSubjectService;
    @Autowired
    private RoleService roleService;

    @Override
    protected BaseService<TradeReceipt, Long> getEntityService() {
        return tradeReceiptService;
    }

    @Override
    protected void checkEntityAclPermission(TradeReceipt entity) {

    }

    @Override
    protected void setupDetachedBindingEntity(Long id) {
        bindingEntity = getEntityService().findDetachedOne(id, "tradeReceiptDetails");
    }

    @Override
    @MetaData(value = "查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    @Override
    public void prepareEdit() {
        super.prepareEdit();
        if (bindingEntity.isNew()) {
            bindingEntity.setVoucher(voucherNumGenerateService.getVoucherNumByType(VoucherTypeEnum.SKD));
            bindingEntity.setVoucherDate(new Date());
            bindingEntity.setVoucherUser(getLogonUser());
            bindingEntity.setVoucherDepartment(getLogonUser().getDepartment());
            bindingEntity.setAccountSubject(accountSubjectService.findByCode("1123"));
            String bizTradeUnitId = getParameter("bizTradeUnitId");
            if (StringUtils.isNotBlank(bizTradeUnitId)) {
                bindingEntity.setBizTradeUnit(bizTradeUnitService.findOne(bizTradeUnitId));
            }
        }
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        if (bindingEntity.isNew()) {
            List<TradeReceiptDetail> tradeReceiptDetails = bindingEntity.getTradeReceiptDetails();
            for (TradeReceiptDetail tradeReceiptDetail : tradeReceiptDetails) {
                tradeReceiptDetail.setTradeReceipt(bindingEntity);
            }
            bindingEntity.setReceiptType(VoucherTypeEnum.SKD);
            checkEntityAclPermission(bindingEntity);
            ExtRevisionListener.setOperationEvent(RevisionType.ADD.name());
            tradeReceiptService.create(bindingEntity);
        } else {
            tradeReceiptService.save(bindingEntity);
        }
        setModel(OperationResult.buildSuccessResult("保存操作成功", bindingEntity));
        return buildDefaultHttpHeaders();
    }

    @MetaData("行项数据")
    public HttpHeaders tradeReceiptDetails() {
        setModel(buildPageResultFromList(bindingEntity.getTradeReceiptDetails()));
        return buildDefaultHttpHeaders();
    }

    public String isDisallowChargeAgainst() {

        if (VoucherStateEnum.REDW.equals(bindingEntity.getVoucherState())) {
            return "已红冲";
        }
        return null;
    }

    public HttpHeaders chargeAgainst() {
        Validation.isTrue(!VoucherStateEnum.REDW.equals(bindingEntity.getVoucherState()), "此单已被红冲");
        if (bindingEntity.getPayTime() != null) {
            User loginUser = this.getLogonUser();
            List<Role> roles = roleService.findR2RolesForUser(loginUser);
            Boolean flag = false;
            for (Role role : roles) {
                if ("ROLE_FI_MGR".equals(role.getCode()) || "ROLE_FI_USER".equals(role.getCode())) {
                    flag = true;
                }
            }
            Validation.isTrue(flag, "已完成收款，非财务人员不能红冲");
            tradeReceiptService.chargeAgainstReceivable(bindingEntity);// 已收款红冲
        } else {
            tradeReceiptService.chargeAgainstSimple(bindingEntity);// 未收款红冲
        }
        setModel(OperationResult.buildSuccessResult("红冲完成"));
        return buildDefaultHttpHeaders();
    }
}